from typing import Callable

import aiomysql
import aioredis
import settings
from fastapi import FastAPI


def startup_handler(app: FastAPI) -> Callable:
    async def startup() -> None:
        # 不处理项目启动错误？？？
        # 默认数据库连接池的最大连接数为10
        # 解决连接池问题: https://www.pythonheidong.com/blog/article/855514/0c4a681752cfb0986096/
        # 把连接池对象加到State对象中
        app.state.pool = await aiomysql.create_pool(
            host=settings.MYSQL_HOST,
            port=settings.MYSQL_PORT,  # .env配置文件中读出来
            user=settings.MYSQL_USER,
            password=settings.MYSQL_PASSWORD,
            db=settings.MYSQL_DB,
            autocommit=False,
        )

        # aioredis.errors.ReplyError: ERR AUTH < password > called without any password configured
        # for the default user.Are you sure your configuration is correct?
        # 需要设置redis密码
        app.state.redis = await aioredis.create_redis_pool(
            f'redis://{settings.REDIS_HOST}:{settings.REDIS_PORT}',
            db=settings.REDIS_DB,
            password=settings.REDIS_PASSWORD,
            encoding='utf8'
        )

    return startup


def shutdown_handler(app: FastAPI) -> Callable:
    async def shutdown() -> None:
        print('close mysql connection pool...')
        await app.state.pool.close()
        await app.state.redis.close()

    return shutdown
